/**
 * copyright (c) 2017-2023 厦门风领科技有限公司
 * https://www.fengling.cn/
 * 
 * API层与原生层的桥接
 * zengbinsi
 * 2021-11-22 21:26:50
 * 2023-10-23 15:31:00
 */


console.log('[TS-API] ===>>>', 'Load API jsb.', cc.sys.isNative);
window.gg = window.gg || {};

if (cc.sys.isNative && !window.qg) {
    gg.jsb = gg.jsb || {};

    if (gg.isLayaAir()) {
        // 适配LayaAir引擎
        if (cc.sys.os === cc.sys.OS_IOS) {
            gg.callStaticMethod = (claName, methodName, ...args) => {
                return PlatformClass.createClass(claName).call(methodName, ...args);
            };
        } else {
            gg.callStaticMethod = (claName, methodName, sigName, ...args) => {
                return PlatformClass.createClass(claName).call(methodName, ...args);
            };
        }
    } else {
        // CocosCreator引擎
        gg.callStaticMethod = (claName, methodName, ...args) => {
            return jsb.reflection.callStaticMethod(claName, methodName, ...args);
        };
    }
    const gg_log = gg.log;
    const gg_info = gg.info;
    const gg_debug = gg.debug;
    const gg_warn = gg.warn;
    const gg_error = gg.error;
    const logToString = (args) => {
        let logStr = new Date().toLocaleTimeString() + '';
        for (let i = 0; i < args.length; i++) {
            args[i] = gg.stringifyJSON(args[i]);
            logStr += ' ' + args[i];
        }
        return logStr;
    };
    const pushLog = (logType, logStr) => {
        const param = gg.stringifyJSON({ t: logType, c: logStr });
        if (gg.isIOS) {
            gg.callStaticMethod('DebugTool', 'pushLog:', param);
        }
    };
    gg.log = (...params) => {
        const logStr = logToString(params);
        gg_log(...params);
        pushLog('L', logStr);
    };
    gg.info = (...params) => {
        const logStr = logToString(params);
        gg_info(...params);
        pushLog('I', logStr);
    };
    gg.debug = (...params) => {
        const logStr = logToString(params);
        gg_debug(...params);
        pushLog('D', logStr);
    };
    gg.warn = (...params) => {
        const logStr = logToString(params);
        gg_warn(...params);
        pushLog('W', logStr);
    };
    gg.error = (...params) => {
        const logStr = logToString(params);
        gg_error(...params);
        pushLog('E', logStr);
    };
    gg.setEnableDebug = (data) => {
        try {
            gg.setDisplayLogPanel(data.enableDebug);
            cc.debug.setDisplayStats(data.enableDebug);
            data && data.success && data.success();
        } catch (error) {
            data && data.fail && data.fail(error);
        }

        data && data.complete && data.complete();
    };
    // ================================================================================================================================================
    //
    // 【获取信息】
    //
    // ================================================================================================================================================

    /** 获取设备唯一标识 */
    gg.getDeviceId = () => {
        return gg.isIOS ? gg.callStaticMethod('DeviceManager', 'getDeviceId') : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'getDeviceId', '()Ljava/lang/String;');
    };

    /** 获取设备唯一标识 */
    gg.getOiad = () => {
        return gg.isIOS ? gg.callStaticMethod('DeviceManager', 'getOaid') : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'getOaid', '()Ljava/lang/String;');
    };
    /** 获取IP地址 */
    gg.getLocalIPAddress = (object) => {
        try {
            const res = gg.isIOS ? gg.callStaticMethod('DeviceManager', 'getLocalIPAddress') : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'getLocalIPAddress', '()Ljava/lang/String;');
            if (res) {
                object.success && object.success({ localip: res });
            } else {
                object.fail && object.fail({ errMsg: '获取网络失败，请检查网络。' });
            }
        } catch (error) {
            object.fail && object.fail({ errMsg: error });
        }
        object.complete && object.complete();
    };
    gg.getNetworkType = (object) => {
        return new Promise((resolve, reject) => {
            try {
                const res = gg.isIOS ? gg.callStaticMethod('DeviceManager', 'getNetworkType') : 'android network type';
                object.success && object.success({ networkType: res });
                resolve({ networkType: res });
            } catch (error) {
                object.fail && object.fail(error);
                reject(error);
            }
            object.complete && object.complete();
        });
    };
    /**
     * 获取App名称
     * @returns 
     */
    gg.getAppName = () => {
        return gg.isIOS ? gg.callStaticMethod(`BaseToolManager`, "getAppName") : gg.callStaticMethod(`com/ily/core/jsb/BaseToolManager`, "getAppName", "()Ljava/lang/String;");
    };

    /**
     * 获取App版本号
     * @returns 
     */
    gg.getAppVersion = () => {
        return gg.isIOS ? gg.callStaticMethod(`BaseToolManager`, "getVersion") : gg.callStaticMethod(`com/ily/core/jsb/BaseToolManager`, "getVersion", "()Ljava/lang/String;");
    };

    /**
     * 获取包名
     * @returns 
     */
    gg.getPackageName = () => {
        return gg.isIOS ? gg.callStaticMethod(`BaseToolManager`, "getPackageName") : gg.callStaticMethod(`com/ily/core/jsb/BaseToolManager`, "getPackageName", "()Ljava/lang/String;");
    };

    /**
     * 获取当前渠道名
     * @returns 
     */
    gg.jsb.getChannel = () => {
        return gg.isIOS ? gg.callStaticMethod(`BaseToolManager`, "getChannel") : gg.callStaticMethod(`com/ily/core/jsb/BaseToolManager`, "getChannel", "()Ljava/lang/String;");
    };
    gg.getSystemInfoSync = () => {
        return new Promise((resolve, reject) => {
            if (gg.__systemInfo) { return resolve(gg.__systemInfo); }

            try {
                gg.__systemInfo = JSON.parse(gg.isIOS ? gg.callStaticMethod(`DeviceManager`, "getSystemInfoSync") : gg.callStaticMethod(`com/ily/core/jsb/DeviceManager`, "getSystemInfoSync", "()Ljava/lang/String;"));

                if (gg.isLayaAir()) {

                } else {
                    gg.__systemInfo.screenWidth = cc.view.getFrameSize().width;
                    gg.__systemInfo.screenHeight = cc.view.getFrameSize().height;
                    gg.__systemInfo.windowWidth = cc.view.getVisibleSize().width;
                    gg.__systemInfo.windowHeight = cc.view.getVisibleSize().height;
                }
                resolve(gg.__systemInfo);
            } catch (error) {
                reject(error);
            }
        });
    };
    gg.getSystemInfoASync = (data) => {
        gg.jsb.getSystemInfoSync().then((res) => {
            data.success && data.success(res);
            data.complete && data.complete();
        }).catch((err) => {
            data.fail && data.fail(err);
            data.complete && data.complete();
        });
    };
    gg.getSystemInfo = (data) => {
        gg.warn('由于历史原因，gg.getSystemInfo 是异步的调用格式，但是是同步返回，需要异步获取系统信息请使用 gg.getSystemInfoASync');
        gg.warn('由于历史原因，gg.getSystemInfo 是异步的调用格式，但是是同步返回，需要异步获取系统信息请使用 gg.getSystemInfoASync');
        gg.warn('由于历史原因，gg.getSystemInfo 是异步的调用格式，但是是同步返回，需要异步获取系统信息请使用 gg.getSystemInfoASync');
        return gg.getSystemInfoASync(data);
    };

    gg.getLaunchOptionsSync = () => {
        return {
            scene: 1001,
            query: {},
            shareTicket: undefined,
            referrerInfo: undefined,
            chatType: 0,
        };
    };
    gg.getEnterOptionsSync = gg.getLaunchOptionsSync;

    /** 获取电量信息和充电状态 */
    gg.getBatteryInfoSync = () => {
        return new Promise((resolve, reject) => {
            try {
                const res = JSON.parse(gg.isIOS ? gg.callStaticMethod(`DeviceManager`, "getBatteryInfoSync") : gg.callStaticMethod(`com/ily/core/jsb/DeviceManager`, "getBatteryInfoSync", "()Ljava/lang/String;"));
                resolve(res);
            } catch (error) {
                reject(error);
            }
        });
    };

    gg.getBatteryInfo = (data) => {
        return gg.getBatteryInfoSync().then((res) => {
            data.success && data.success(res);
            data.complete && data.complete();
        }).catch((err) => {
            data.fail && data.fail(err);
            data.complete && data.complete();
        });
    };

    // ================================================================================================================================================
    //
    // 【基础】
    //
    // ================================================================================================================================================
    gg.login = (data) => {
        gg.log('调用原生登录gg.log()');
        try {
            let code = cc.sys.localStorage.getItem('FLUID') || gg.callStaticMethod(`com/ily/core/jsb/DeviceManager`, "getDeviceId", "()Ljava/lang/String;");
            if (!code) {
                code = `FLUID_${Date.now()}${Math.floor(Math.random() * 10000)}`;
            }
            gg.log('code:', code);
            cc.sys.localStorage.setItem('FLUID', code);
            data && data.success && data.success({ code });
        } catch (error) {
            data && data.fail && data.fail(error);
        }
        data && data.complete && data.complete();
    };

    gg.openBrowserUrl = (url) => {
        gg.isIOS ? gg.callStaticMethod('DeviceManager', 'openBrowserUrl:', url) : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'openBrowserUrl', '(Ljava/lang/String;)V', url);
    };

    gg.openWebViewUrl = (url) => {
        gg.isIOS ? gg.callStaticMethod('BaseToolManager', 'pushWebViewWithH5:', url) : gg.callStaticMethod('com/ily/core/jsb/BaseToolManager', 'pushWebViewWithH5', '(Ljava/lang/String;)V', url);
    };

    gg.setClipboardData = (object) => {
        return new Promise((resolve, reject) => {
            try {
                gg.isIOS ? gg.callStaticMethod('DeviceManager', 'setClipboardData:', object.data) : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'setClipboardData', '(Ljava/lang/String;)V', object.data);
                object.success && object.success({ data: object.data });
                resolve();
            } catch (error) {
                object.fail && object.fail(error);
                reject(error);
            }
            object.complete && object.complete();
        });
    };
    gg.getClipboardData = (object) => {
        return new Promise((resolve, reject) => {
            try {
                const res = gg.isIOS ? gg.callStaticMethod('DeviceManager', 'getClipboardData') : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'getClipboardData', '()Ljava/lang/String;');
                object.success && object.success({ data: res });
                resolve({ data: res });
            } catch (error) {
                object.fail && object.fail(error);
                reject(error);
            }
            object.complete && object.complete();
        });
    };



    // 【设备】
    gg.vibrateShort = (object) => {
        return new Promise((resolve, reject) => {
            try {
                gg.isIOS ? gg.callStaticMethod('DeviceManager', 'vibrator:', true) : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'vibrator', '(II)V', 450, 500);
                object.success && object.success();
                resolve();
            } catch (error) {
                object.fail && object.fail(error);
                reject(error);
            }
            object.complete && object.complete();
        });
    };
    gg.vibrateLong = (data) => {
        return new Promise((resolve, reject) => {
            try {
                gg.isIOS ? gg.callStaticMethod('DeviceManager', 'vibrator:', false) : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'vibrator', '(II)V', 1500, 1000);
                object.success && object.success();
                resolve();
            } catch (error) {
                object.fail && object.fail(error);
                reject(error);
            }
            object.complete && object.complete();
        });
    };
    gg.setScreenBrightness = (object) => {
        return new Promise((resolve, reject) => {
            try {
                gg.isIOS ? gg.callStaticMethod('DeviceManager', 'setScreenBrightness:', object.value) : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'setScreenBrightness', '(F)V', object.value);
                object.success && object.success();
                resolve();
            } catch (error) {
                object.fail && object.fail(error);
                reject(error);
            }
            object.complete && object.complete();
        });
    };
    gg.getScreenBrightness = (object) => {
        return new Promise((resolve, reject) => {
            try {
                const res = gg.isIOS ? gg.callStaticMethod('DeviceManager', 'getScreenBrightness') : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'getScreenBrightness', '()F');
                object.success && object.success({ value: res });
                resolve({ value: res });
            } catch (error) {
                object.fail && object.fail(error);
                reject(error);
            }
            object.complete && object.complete();
        });
    };
    gg.setKeepScreenOn = (object) => {
        return new Promise((resolve, reject) => {
            try {
                gg.isIOS ? gg.callStaticMethod('DeviceManager', 'setKeepScreenOn:', object.keepScreenOn) : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'setKeepScreenOn', '(Z)V', object.keepScreenOn);
                object.success && object.success();
                resolve();
            } catch (error) {
                object.fail && object.fail(error);
                reject(error);
            }
            object.complete && object.complete();
        });
    };




    // 【UI】
    gg.showToast = (data) => {
        return new Promise((resolve, reject) => {
            try {
                const isLong = data.duration > 1200;
                data.title = data.title || '';

                if (gg.isIOS) {
                    data.mask = data.mask ? 1 : 0;
                    gg.callStaticMethod('DeviceManager', 'showToast:', gg.stringifyJSON(data));
                } else {
                    gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'showToast', '(Ljava/lang/String;Z)V', data.title, isLong);
                }
                data.success && data.success();
                resolve();
            } catch (error) {
                data.fail && data.fail(error);
                reject(error);
            }
            data.complete && data.complete();
        });
    };
    gg.showModal = (data) => {
        return new Promise((resolve, reject) => {
            try {
                const confirmKey = `showModel_confirm_${data.content}`;
                const cancelKey = `showModel_cancell_${data.content}`;
                window[confirmKey] = () => {
                    window[confirmKey] = undefined;
                    const res = { confirm: true, cancel: false };
                    data.success && data.success(res);
                    reject(res);
                };
                window[cancelKey] = () => {
                    window[cancelKey] = undefined;
                    const res = { confirm: false, cancel: true };
                    data.success && data.success(res);
                    reject(res);
                };

                gg.isEmpty(data.title) && (data.title = '');
                gg.isEmpty(data.content) && (data.content = '');
                gg.isEmpty(data.showCancel) && (data.showCancel = true);
                gg.isEmpty(data.cancelText) && (data.cancelText = '取消');
                gg.isEmpty(data.cancelColor) && (data.cancelColor = '#000000');
                gg.isEmpty(data.confirmText) && (data.confirmText = '确定');
                gg.isEmpty(data.confirmColor) && (data.confirmColor = '#576B95');
                gg.isEmpty(data.editable) && (data.editable = false);
                const model = gg.stringifyJSON({ title: data.title, content: data.content, cancelText: data.cancelText, confirmText: data.confirmText });

                if (gg.isIOS) {
                    gg.callStaticMethod('DeviceManager', 'showModal:cancelCallbackName:confirmCallbackName:', model, `window['${cancelKey}']`, `window['${confirmKey}']`);
                } else {
                    gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'showModal', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V', model, `window['${cancelKey}']`, `window['${confirmKey}']`);
                }
            } catch (error) {
                data.fail && data.fail(error);
                reject(error);
            }
            data.complete && data.complete();
        });
    };
    gg.exitMiniProgram = (data) => {
        gg.info('gg.exitMiniProgram(data)函数即将废弃，请使用gg.exitApp(data)函数代替。');
        return gg.exitApp(data);
    };
    gg.exitApp = (data) => {
        return new Promise((resolve, reject) => {
            try {
                gg.isIOS ? gg.callStaticMethod('DeviceManager', 'exitApp') : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'exitApp', '()V');
                data && data.success && data.success();
                resolve();
            } catch (error) {
                data && data.fail && data.fail(error);
                reject(error);
            }
            data && data.complete && data.complete();
        });
    };





    // ================================================================================================================================================
    //
    // 【防沉迷】
    //
    // ================================================================================================================================================
    /**
     * 实名认证
     * @param {*} data 
     */
    gg.checkIsUserAdvisedToRest = (data) => {
        return new Promise((resolve, reject) => {
            try {
                gg.isIOS ? gg.gg.callStaticMethod('BaseToolManager', 'checkRealName') : gg.callStaticMethod('com/ily/core/jsb/BaseToolManager', 'checkRealName', '()V');
                data.success && data.success();
                resolve();
            } catch (error) {
                data.fail && data.fail(error);
                reject(error);
            }
            data.complete && data.complete();
        });
    };

    // ================================================================================================================================================
    //
    // 【其它】
    //
    // ================================================================================================================================================
    gg.downloadFile = (data) => {
        // 设置文件下载的全局回调
        window['gg_downloadFile_callback' + data.url] = (err, res) => {
            window['gg_downloadFile_callback' + data.url] = undefined;

            if (err) {
                err = gg.parseJSON(err);
                return data.fail && data.fail(err);
            }

            res = gg.parseJSON(res);
            data.success && data.success(res);
            data.complete && data.complete(res);
        };
        const url = `${data.url}?v=${Math.floor(Date.now() / 1000 / 60)}`;

        if (gg.isIOS) {
            const methodName = 'downloadFile:storeFile:progressCallbackName:completeCallbackName:';
            gg.callStaticMethod('BaseToolManager', methodName, url, data.filePath, undefined, `window['gg_downloadFile_callback${data.url}']`);
        } else {
            const clsName = 'com/ily/core/jsb/BaseToolManager';
            const methodSignature = '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V';
            gg.callStaticMethod(clsName, 'downloadFile', methodSignature, url, data.filePath, undefined, `window['gg_downloadFile_callback${data.url}']`);
        }
    };

    gg.unzipFile = (data) => {
        // 设置文件下载的全局回调
        window['gg_unzipFile_callback' + data.url] = (err, res) => {
            window['gg_unzipFile_callback' + data.url] = undefined;

            if (err) {
                err = gg.parseJSON(err);
                return data.fail && data.fail(err);
            }

            res = gg.parseJSON(res);
            data.success && data.success(res);
            data.complete && data.complete(res);
        };

        if (gg.isIOS) {
            const methodName = 'unzipFile:saveDir:progressCallbackName:completeCallbackName:';
            gg.callStaticMethod('BaseToolManager', methodName, data.zipFilePath, data.targetPath, undefined, `window['gg_unzipFile_callback${data.url}']`);
        } else {
            const clsName = 'com/ily/core/jsb/BaseToolManager';
            const methodSignature = '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V';
            gg.callStaticMethod(clsName, 'unzipFile', methodSignature, data.zipFilePath, data.targetPath, undefined, `window['gg_unzipFile_callback${data.url}']`);
        }
    };

    /** 打开应用商店 */
    gg.openAppStoreWithAppId = (data) => {
        return new Promise((resolve, reject) => {
            try {
                gg.isIOS ? gg.callStaticMethod('DeviceManager', 'jumpAppStoreWithAppID:', data.appId) : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'jumpAppStoreWithAppID', '(Ljava/lang/String;)V', data.appId);
                data.success && data.success();
                resolve();
            } catch (error) {
                data.fail && data.fail(error);
                reject(error);
            }
            data.complete && data.complete();
        });
    };

    gg.navigateToMiniProgram = (data) => {
        return new Promise((resolve, reject) => {
            try {
                const schemes = '';
                gg.isIOS ? gg.callStaticMethod('DeviceManager', 'jumpAppSchemes:AppID:', schemes, data.appId) : gg.callStaticMethod('com/ily/core/jsb/DeviceManager', 'navigateToMiniProgram', '(Ljava/lang/String;)V', data.appId);
                data.success && data.success();
                resolve();
            } catch (error) {
                data.fail && data.fail(error);
                reject(error);
            }
            data.complete && data.complete();
        });
    };

    gg.setDisplayLogPanel = (isDisplay) => {
        if (gg.isIOS) {
            gg.callStaticMethod('DebugTool', 'setDisplayLogPanel:', isDisplay);
        } else {
            gg.warn('该平台暂未实现gg.setDisplayLogPanel()方法。');
        }
    };

    // ================================================================================================================================================
    //
    // 【统计】
    //
    // ================================================================================================================================================
    const emitEventAnalytics = (data) => {
        data.eventName = data.eventName || data.key;

        if (gg.isIOS) {
            data.value = gg.stringifyJSON(data.value || {});
            gg.callStaticMethod('JSBridgeManager', 'emitEventAnalytics:', gg.stringifyJSON(data));
        } else {
            const value = data.value || {};
            data.value = undefined;
            data = { ...data, ...value };
            gg.callStaticMethod('com/ily/core/jsb/JSBridgeManager', 'emitEventAnalytics', '(Ljava/lang/String;)V', gg.stringifyJSON(data));
        }
    };

    gg.sendEvent = (eventName, params) => {
        gg.log('发送统计事件：', eventName, params);
        emitEventAnalytics({
            analyticsEventType: 'ANALYTICS_SEND_EVENT',
            key: eventName,
            value: params || {},
        });
    };

    gg.onLevelStart = (level, params) => {
        const eventName = `开始第${level}关`;
        gg.log('发送统计事件：', eventName, params);
        emitEventAnalytics({
            analyticsEventType: 'ANALYTICS_SEND_EVENT',
            key: eventName,
            value: params || {},
        });
    };

    gg.onLevelEnd = (level, params) => {
        const eventName = `结束第${level}关`;
        gg.log('发送统计事件：', eventName, params);
        emitEventAnalytics({
            analyticsEventType: 'ANALYTICS_SEND_EVENT',
            key: eventName,
            value: params || {},
        });
    };

    gg.onPageStart = (pageName) => {
        gg.log('发送页面统计事件-开始：', pageName);
        emitEventAnalytics({
            analyticsEventType: 'ANALYTICS_PAGE_START',
            key: pageName
        });
    };

    gg.onPageEnd = (pageName) => {
        gg.log('发送页面统计事件-结束：', pageName);
        emitEventAnalytics({
            analyticsEventType: 'ANALYTICS_PAGE_END',
            key: pageName
        });
    };

    gg.onProfileSignIn = (userId) => {
        gg.log('发送自有id登录事件：', userId);
        emitEventAnalytics({
            analyticsEventType: 'ANALYTICS_SIGN_IN',
            key: userId
        });
    };

    gg.onProfileSignOff = (userId) => {
        gg.log('发送自有id登出事件：', userId);
        emitEventAnalytics({
            analyticsEventType: 'ANALYTICS_SIGN_OUT',
            key: userId
        });
    };

    // ================================================================================================================================================
    //
    // 【广告】
    //
    // ================================================================================================================================================

    gg.createBannerAd = (data) => {
        gg.log('调用createBannerAd广告  gg.createBannerAd:', gg.stringifyJSON(data));
        let ad = BannerAd.ad[data.adUnitId];
        if (!ad) {
            ad = new BannerAd(data);
        }
        return ad;
    };

    gg.createRewardedVideoAd = (data) => {
        gg.log('调用createRewardedVideoAd激励视频');
        let ad = RewardedVideoAd.ad[data.adUnitId];
        if (!ad) {
            ad = new RewardedVideoAd(data);
        }
        return ad;
    };

    gg.createInterstitialAd = (data) => {
        gg.log('调用createInterstitialAd激励视频');
        let ad = InterstitialAd.ad[data.adUnitId];
        if (!ad) {
            ad = new InterstitialAd(data);
        }
        return ad;
    };

    /**
     * 初始化广告
     * @returns 
     */
    gg.adInit = () => {
        gg.log('调用adInit 11111初始化广告');
        return gg.isIOS ? gg.warn('该平台暂未实现eventADInit()方法。') : gg.callStaticMethod(`com/ily/core/jsb/JSBridgeManager`, "eventADInit", "()V");
    };

    /**
     * 触发原生广告事件
     * @param {*} data {adType: string, adEventType: string, adUnitId: string, callback: string, userData: any}
     */
    gg.jsb.emitEventAD = (data) => {
        data = gg.stringifyJSON(data);
        gg.log('调用Native广告事件：', data);
        if (gg.isIOS) {
            gg.callStaticMethod('JSBridgeManager', "emitEventAD:", gg.stringifyJSON(data));
        } else {
            gg.callStaticMethod("com/ily/core/jsb/JSBridgeManager", "emitEventAD", "(Ljava/lang/String;)V", data);
        }
    };

    gg.payment = (data) => {
        return new Promise((resolve, reject) => {
            const callbackName = `payment_${Date.now()}`;
            window[`${callbackName}`] = (err, res) => {
                window[`${callbackName}`] = undefined;
                if (err) {
                    data.fail && data.fail(err);
                    reject(err);
                    return data.complete && data.complete();
                }

                res = res || {};
                res.errMsg = 'ok';

                data.success && data.success(res);
                resolve(res);
                data.complete && data.complete();
            };
            data.callback = `window.${callbackName}`;
            data = gg.stringifyJSON(data);
            data.callback = 'gg.payment.callback';

            try {
                gg.log('调用Native支付事件：', data);
                if (gg.isIOS) {
                    gg.callStaticMethod('JSBridgeManager', "emitEventApplePay:", data);
                } else {
                    gg.callStaticMethod("com/common/jsb/JSBridgeManager", "emitEventGooglePay", "(Ljava/lang/String;)V", data);
                }
            } catch (error) {
                data.fail && data.fail(error);
                reject(error);
                data.complete && data.complete();
            }
        });
    };

    // 激励式广告场景曝光
    gg.onReportUserBehaviorBranchAnalytics = (data) => { gg.log('该平台暂未实现gg.reportUserBehaviorBranchAnalytics()方法。'); };
}